import pandas as pd
import numpy as np
import json

# 读取CSV数据
df = pd.read_csv('../PointDownLoad/A6顶板底钢筋网_分裂坐标.csv')

# 提取所有以 x, y, z 开头的列
x_columns = [col for col in df.columns if col.startswith('x')]
y_columns = [col for col in df.columns if col.startswith('y')]
z_columns = [col for col in df.columns if col.startswith('z')]

# 提取所有以 x, y, z 开头的列
x_columns = [col for col in df.columns if col.startswith('x')]
y_columns = [col for col in df.columns if col.startswith('y')]
z_columns = [col for col in df.columns if col.startswith('z')]

# 计算最小值
x_min = int(df[x_columns].min().min())
y_min = int(df[y_columns].min().min())
z_min = int(df[z_columns].min().min())

# 对所有以 x 开头的列的值减去 x_min
df[x_columns] = df[x_columns] - x_min

# 对所有以 y 开头的列的值减去 y_min
df[y_columns] = df[y_columns] - y_min

# 对所有以 z 开头的列的值减去 z_min
df[z_columns] = df[z_columns] - z_min


# 计算直线段长度的函数（弯钩暂时不考虑  考虑的话在加代码处理）
def calculate_length(row):
    # 提取坐标，形成元组列表
    coordinates = []
    for i in range(1, len(x_columns) + 1):
        if not pd.isna(row[f'x{i}']):
            coordinates.append((row[f'x{i}'], row[f'y{i}'], row[f'z{i}']))

    total_length = 0
    if (abs(row['Start Angle']) == 135 and abs(row['End Angle']) == 135 and len(x_columns) == 6):
        point1 = coordinates[2]
        point2 = coordinates[3]
        distance = np.sqrt((point2[0] - point1[0]) ** 2 + (point2[1] - point1[1]) ** 2 + (point2[2] - point1[2]) ** 2)
        total_length += distance
    elif (abs(row['Start Angle']) == 135 and abs(row['End Angle']) == 135 and len(x_columns) > 6):
        point1 = coordinates[2]
        point2 = coordinates[3]
        distance = np.sqrt((point2[0] - point1[0]) ** 2 + (point2[1] - point1[1]) ** 2 + (point2[2] - point1[2]) ** 2)
        total_length += distance
    elif (abs(row['Start Angle']) == 135 and abs(row['End Angle']) != 135):
        point1 = coordinates[2]
        point2 = coordinates[3]
        distance = np.sqrt((point2[0] - point1[0]) ** 2 + (point2[1] - point1[1]) ** 2 + (point2[2] - point1[2]) ** 2)
        total_length += distance
    elif (abs(row['Start Angle']) != 135 and abs(row['End Angle']) == 135):
        point1 = coordinates[len(x_columns) - 3]
        point2 = coordinates[len(x_columns) - 4]
        distance = np.sqrt((point2[0] - point1[0]) ** 2 + (point2[1] - point1[1]) ** 2 + (point2[2] - point1[2]) ** 2)
        total_length += distance
    elif (abs(row['Start Angle']) != 135 and abs(row['End Angle']) != 135):
        point1 = coordinates[0]
        point2 = coordinates[1]
        distance = np.sqrt((point2[0] - point1[0]) ** 2 + (point2[1] - point1[1]) ** 2 + (point2[2] - point1[2]) ** 2)
        total_length += distance

    return total_length


# 计算两根钢筋的间隙
def calculate_space(row, next_row):
    if next_row is None:
        return 0

    current_end = (row['x1'], row['y1'], row['z1'])
    next_start = (next_row['x1'], next_row['y1'], next_row['z1'])

    distance = np.sqrt((next_start[0] - current_end[0]) ** 2 +
                       (next_start[1] - current_end[1]) ** 2 +
                       (next_start[2] - current_end[2]) ** 2)

    return distance


# 应用函数计算每根钢筋的长度
df['Length'] = df.apply(calculate_length, axis=1)

# 设置阈值  判断横筋纵筋
threshold = df['Length'].mean()

# Classify as 横筋(1) or 纵筋(0)
df['Type'] = df['Length'].apply(lambda x: '0' if x >= threshold else '1')

# 初始化一个space列为0
df['space'] = 0

# 计算每一条记录和下一条记录之间的距离
for i in range(len(df) - 1):
    df.loc[i, 'space'] = calculate_space(df.iloc[i], df.iloc[i + 1])

# 对最后一条记录，space字段设为0
df.loc[len(df) - 1, 'space'] = 0

# 创建一个新的DataFrame来保存横筋和纵筋的坐标
columns = ['meshNo', 'Size', 'angle01', 'length01', 'angle02', 'length02', 'Type', 'x_start', 'y_start', 'x_end',
           'y_end', 'Length', 'space']
coordinates_df = pd.DataFrame(columns=columns)

# 提取横筋的坐标
horizontal_rebars = df[df['Type'] == '1']
x_start = ''
x_end = ''
y_start = ''
y_end = ''


def calculate_xy(row):
    x_start = ''
    x_end = ''
    y_start = ''
    y_end = ''
    if (abs(row['Start Angle']) == 135 and abs(row['End Angle']) == 135 and len(x_columns) == 6):
        x_start = 'x3'
        x_end = 'x4'
        y_start = 'y3'
        y_end = 'y4'

    elif (abs(row['Start Angle']) == 135 and abs(row['End Angle']) == 135 and len(x_columns) > 6):
        x_start = 'x3'
        x_end = 'x4'
        y_start = 'y3'
        y_end = 'y4'

    elif (abs(row['Start Angle']) == 135 and abs(row['End Angle']) != 135):
        x_start = 'x3'
        x_end = 'x4'
        y_start = 'y3'
        y_end = 'y4'

    elif (abs(row['Start Angle']) != 135 and abs(row['End Angle']) == 135):
        x_start = 'x' + str(len(x_columns) - 3)
        x_end = 'x' + str(len(x_columns) - 2)
        y_start = 'y' + str(len(x_columns) - 3)
        y_end = 'y' + str(len(x_columns) - 2)

    elif (abs(row['Start Angle']) != 135 and abs(row['End Angle']) != 135):
        x_start = 'x1'
        x_end = 'x2'
        y_start = 'y1'
        y_end = 'y2'

    return x_start, y_start, x_end, y_end

# 将结果拆分为 x_start, x_end, y_start, y_end
x_start, y_start, x_end, y_end = calculate_xy(horizontal_rebars.iloc[0])

horizontal_coords = horizontal_rebars[
    ['Mesh No', 'Size', 'Start Angle', 'Start Length', 'End Angle', 'End Length', 'Type', x_start, y_start, x_end,
     y_end, 'Length', 'space']].copy()
horizontal_coords.columns = ['meshNo', 'Size', 'angle01', 'length01', 'angle02', 'length02', 'Type', 'x_start',
                             'y_start', 'x_end', 'y_end', 'Length', 'space']

# 提取纵筋的坐标
vertical_rebars = df[df['Type'] == '0']
vertical_coords = vertical_rebars[
    ['Mesh No', 'Size', 'Start Angle', 'Start Length', 'End Angle', 'End Length', 'Type', 'x1', 'y1', 'x2',
     'y2', 'Length', 'space']].copy()
vertical_coords.columns = ['meshNo', 'Size', 'angle01', 'length01', 'angle02', 'length02', 'Type', 'x_start',
                           'y_start', 'x_end', 'y_end', 'Length', 'space']

# 合并横筋和纵筋的坐标
coordinates_df = pd.concat([horizontal_coords, vertical_coords], ignore_index=True)

# 初始化JSON结构
json_output = {
    "meshNo": 1,
    "planNum": 1,
    "finishNum": 0,
    "zdiameter": 0,
    "angle01": 0,
    "length01": 0,
    "angle02": 0,
    "length02": 0,
    "angle03": 0,
    "length03": 0,
    "angle04": 0,
    "length04": 0,
    "bendPosition01": 0,
    "bendPosition02": 0,
    "originPoint": [0, 0],
    "hSubs": [],
    "zSubs": []
}

# 填充hSubs和zSubs字段
h_index = 1
z_index = 1
# x_total = 0
# y_total = 0
# for _, row in coordinates_df.iterrows():
#     if row["Type"] == '1':  # 横筋
#         json_output['angle01'] = int(row['angle01'])
#         json_output['length01'] = row['length01']
#         json_output['angle02'] = int(row['angle02'])
#         json_output['length02'] = row['length02']
#         if (h_index == 1):
#             json_output["hSubs"].append({
#                 "index": h_index,
#                 "start": [x_total, 0],
#                 "end": [x_total, int(row['Length'])],
#                 "hDiameter ": row["Size"]
#             })
#             x_total -= row['space']
#             x_total = int(x_total)
#         else:
#             json_output["hSubs"].append({
#                 "index": h_index,
#                 "start": [x_total, 0],
#                 "end": [x_total, int(row['Length'])],
#                 "hDiameter ": row["Size"]
#             })
#             x_total -= row['space']
#             x_total = int(x_total)
#         h_index += 1
#     elif row["Type"] == '0':  # 纵筋
#         json_output['zdiameter'] = int(row['Size'])
#         if (z_index == 1):
#             json_output["zSubs"].append({
#                 "index": z_index,
#                 "start": [0, y_total],
#                 "end": [-int(row["Length"]), y_total]
#             })
#             y_total += row['space']
#             y_total = int(y_total)
#         else:
#             json_output["zSubs"].append({
#                 "index": z_index,
#                 "start": [0, y_total],
#                 "end": [-int(row["Length"]), y_total]
#             })
#             y_total += row['space']
#             y_total = int(y_total)
#         z_index += 1

# 将结果保存为JSON文件
for _, row in coordinates_df.iterrows():
    if row["Type"] == '1':  # 横筋
        json_output['angle01'] = int(row['angle02'])
        json_output['length01'] = row['length02']
        json_output['angle02'] = int(row['angle01'])
        json_output['length02'] = row['length01']
        json_output["hSubs"].append({
            "index": h_index,
            "start": [int(row["x_end"]), int(row["y_end"])],
            "end": [int(row["x_start"]), int(row["y_start"])],
            "hDiameter ": row["Size"]
        })
        h_index += 1
    elif row["Type"] == '0':  # 纵筋
        json_output['zdiameter'] = row['Size']
        json_output["zSubs"].append({
            "index": z_index,
            "start": [int(row["x_start"]), int(row["y_start"])],
            "end": [int(row["x_end"]), int(row["y_end"])]
        })
        z_index += 1

output_file_path = 'A6顶板底钢筋网.json'
with open(output_file_path, 'w') as json_file:
    json.dump(json_output, json_file, indent=4)
